from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect
import datetime
from web import models
from django.conf import settings

class Tracer:
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None

class AuthMiddleware(MiddlewareMixin):
    def process_request(self,request):
        """如果用户已经登录，则request 中赋值"""

        request.tracer = Tracer()
        user_id = request.session.get('user_id',0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        # tracer 是自定义的属性
        request.tracer.user = user_obj

        # 添加白名单
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            # 若访问的页面在白名单中，则可以继续访问
            return

        # 若访问的页面不在白名单中，则继续判断用户是否登录
        if not request.tracer.user:
            # 若用户未登录，则返回到登录页面
            return redirect('login')



        # 登录成功后，访问后台管理时：获取当前用户拥有的额度
        # 方式一：免费额度在交易记录中存储
        # 获取当前用户 ID 最大值（最近交易记录）
        _object = models.Transaction.objects.filter(user=user_obj,status=2).order_by('-id').first()
        # 判断是否过期
        current_datetime = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_datetime:
            _object = models.Transaction.objects.filter(user=user_obj,status=2,price_policy__category=1).first()
        request.tracer.price_policy = _object.price_policy


    def process_view(self,request,view,arg,kwarg):
        # 判断URL是否以manage 开头，如果是则判断项目项目ID是否由我创建 or 参与
        if not request.path_info.startswith('/manage/'):
            return

        # project_id 是否由我创建 or 参与
        project_id = kwarg.get('project_id')
        project_obj = models.Project.objects.filter(id=project_id,creator=request.tracer.user).first()
        if project_obj:
            request.tracer.project = project_obj
            return

        # 是否是我参与的项目
        participant_obj = models.Participant.objects.filter(user=request.tracer.user,project_id=project_id).first()
        if participant_obj:
            request.tracer.project = participant_obj.project
            return
        # 以上那个都不成立则跳转到指定页面
        redirect('project_list')